//
// Created by 吴竹亚 on 2023/3/14.
//
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int no;
    int score;
} Stu;

typedef struct StackNode {
    Stu *stu;
    struct StackNode *next;
} StackNode, *LinkStack;

void initStack(LinkStack &linkStack);

Stu *pop(LinkStack &linkStack);

void push(LinkStack &linkStack, Stu &stu);

Stu *getTop(LinkStack &linkStack);

int StackLength(LinkStack &linkStack);

void initValue(LinkStack &linkStack);

void show(LinkStack &linkStack);

int main() {
    //定义一个栈
    //将十个同学信息入栈
    //打印栈的长度
    //输出所有数据
    LinkStack linkStack;
    initStack(linkStack);
    initValue(linkStack);
    printf("the stack length is %d\n", StackLength(linkStack));
    show(linkStack);

    //出栈一个数据元素，并将这个数据元素打印出来
    //打印栈的长度
    //输出所有数据
    Stu *s1 = pop(linkStack);
    printf("the pop stu no is %d, score is %d\n", s1->no, s1->score);
    printf("the stack length is %d\n", StackLength(linkStack));
    show(linkStack);

    //入栈一个数据元素（自己学号-1）同学
    //打印栈的长度
    //输出所有数据
    Stu s2 = {42, 5};
    push(linkStack, s2);
    printf("the stack length is %d\n", StackLength(linkStack));
    show(linkStack);

    //读出栈顶元素的值
    //打印栈的长度
    //输出所有数据
    Stu *s3 = getTop(linkStack);
    printf("the getPop stu no is %d, score is %d\n", s3->no, s3->score);
    printf("the stack length is %d\n", StackLength(linkStack));
    show(linkStack);
    return 0;
}

void initStack(LinkStack &linkStack) {
    linkStack = new StackNode;
    linkStack->stu = NULL;
    linkStack->next = NULL;
}

Stu *pop(LinkStack &linkStack) {
    if (linkStack->next != NULL) {
        Stu *stu = linkStack->next->stu;
        linkStack->next = linkStack->next->next;
        return stu;
    }
    return NULL;
}

void push(LinkStack &linkStack, Stu &stu) {
    LinkStack next = new StackNode;
    next->next = linkStack->next;
    next->stu = &stu;
    linkStack->next = next;
}

Stu *getTop(LinkStack &linkStack) {
    return linkStack->next->stu;
}

int StackLength(LinkStack &linkStack) {
    LinkStack p = linkStack;
    int i;
    for (i = 0; p->next != NULL; ++i) {
        p = p->next;
    }
    return i;
}

void initValue(LinkStack &linkStack) {
    for (int i = 0; i < 10; ++i) {
        Stu *stu = new Stu;
        stu->no = i + 43;
        stu->score = 100 - i * 10;
        push(linkStack, *stu);
    }
}

void show(LinkStack &linkStack) {
    LinkStack p = linkStack;
    for (int i = 0; p->next != NULL; ++i) {
        p = p->next;
        printf("the %d stu, no is %d, score is %d\n", i + 1, p->stu->no, p->stu->score);
    }
}